package com.jinzhi.jzweb.controller;


import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzweb.StuSignUpComVos;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * <pre>
 * 考生报名   第一次加密
 * </pre>
 * <small> 2023-05-05 08:52:02 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/stuSignUpCom")
public class StuSignUpComController extends BaseController {
	@Autowired
	private StuSignUpComService stuSignUpComService;

	@Autowired
	private StuSignUpComService stuSignUpService;
	@Autowired
	private UserService userService;
	@Autowired
	private ExaminationBatchComService examinationBatchService;
	@Autowired
	private ExaminationAnswerSheetComService examinationAnswerSheetService;

	@Autowired
	private DictService dictService;


	@Autowired
	private MarkService markService;
	@Log("考生重考报名")
	@PostMapping("/reExam")
	@ResponseBody
	@RequiresPermissions("jzweb:stuSignUpCom:reExam")
	public Result<String> reExam(Long id) {
		StuSignUpComDO s = stuSignUpService.selectById(id);
		s.setState(8);//将考试转态“已考完”更改为“考试中”
		stuSignUpService.updateById(s);
		Map map = new HashMap<String,String>();
		map.put("stu_sign_id", id);
		//删除考生成绩
		markService.delete(new EntityWrapper<MarkDO>().eq("sign_id",id));
		boolean b=	examinationAnswerSheetService.deleteByMap(map);


		return Result.ok("操作成功！");


	}


	@GetMapping()
	@RequiresPermissions("jzweb:stuSignUpCom:stuSignUpCom")
	String StuSignUpCom(Integer types,Model model){
		model.addAttribute("types",types);
	    return "jzweb/stuSignUpCom/stuSignUpCom";
	}


	/**
	 * 一次加密
	 * @param types
	 * @param model
	 * @return
	 */
	@GetMapping("/num1")
	@RequiresPermissions("jzweb:stuSignUpCom:stuSignUpCom")
	String stuSignUpComNum1(Integer types,Model model){
		model.addAttribute("types",types);
		return "jzweb/stuSignUpCom/stuSignUpComNum1";
	}



	@GetMapping("/stuSignUpComNum2")
	@RequiresPermissions("jzweb:stuSignUpCom:stuSignUpComNum2")
	String stuSignUpComNum2(Integer types,Model model){
		model.addAttribute("types",types);
		return "jzweb/stuSignUpCom/stuSignUpComNum2";
	}


	/**
	 * 赛场录入
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/stuSignUpComEnter/{id}")
	@RequiresPermissions("jzweb:stuSignUpCom:resetPwd")
	String stuSignUpComEnter(@PathVariable("id") Long id,Model model){
	StuSignUpComDO stuSignUpComDO=	stuSignUpService.selectById(id);
		model.addAttribute("stuSignUpCom",stuSignUpComDO);
		return "jzweb/stuSignUpCom/enter";
	}

	/**
	 * 导如模板 信息
	 * @throws Exception
	 */
	@GetMapping("/exportList")
	@ResponseBody
	public void exportlist( HttpServletRequest request, HttpServletResponse responseexa) throws Exception{

		List<StuSignUpComVos> list = new LinkedList<>();
		//导出操作
		EasyPoiUtil.exportExcel(list, "选手导入模板", "选手导入模板", StuSignUpComVos.class, "选手导入模板", responseexa);

	}

		/**
         * 第一次加密选手导出信息
         *
         * @param response
         */
	@GetMapping("/downloadImportStu")
	@RequiresPermissions("jzweb:stuSignUpCom:import")
	@ResponseBody
	public Result<String> downloadImportTemplate(HttpServletResponse response,StuSignUpComDO stuSignUpComDTO) {
		Result result = new Result();
		try {
			List<StuSignUpComVo> list1 = new LinkedList<>();
			Wrapper<StuSignUpComDO> wrapper = new EntityWrapper<StuSignUpComDO>().
					orderBy("id", false);
	/*		if(StringUtil.notEmpty(stuSignUpComDTO.getCompetitionType())){
				wrapper.addFilter("{0} like CONCAT('%',competition_type,'%')", stuSignUpComDTO.getCompetitionType());
			}*/
			if(StringUtil.notEmpty(stuSignUpComDTO.getName())){
				wrapper.like("name",stuSignUpComDTO.getName());
			}
			if(StringUtils.isNotBlank(stuSignUpComDTO.getCbatchName())){
				wrapper.eq("cbatch_id",stuSignUpComDTO.getCbatchName());
			}

			if(StringUtil.notEmpty(stuSignUpComDTO.getIdNumber())){
				wrapper.like("id_number", stuSignUpComDTO.getIdNumber());
			}
			List<StuSignUpComDO> list=	stuSignUpComService.selectList(wrapper);
			for(StuSignUpComDO li:list){
				StuSignUpComVo stuSignUpComVo=new StuSignUpComVo();
				stuSignUpComVo.setComNums(li.getComNums());
				stuSignUpComVo.setName(li.getName());
				stuSignUpComVo.setIdNumber(li.getIdNumber());
				stuSignUpComVo.setTicketNumber(li.getTicketNumber());
				stuSignUpComVo.setNotes(li.getNotes());
				stuSignUpComVo.setUnitName(li.getUnitName());
				stuSignUpComVo.setTeacherName(li.getTeacher());
				stuSignUpComVo.setNum1(li.getNum1());
				stuSignUpComVo.setNum2(li.getNum2());
				stuSignUpComVo.setSignUpTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(li.getSignUpTime()));
			/*	if (li.getCompetitionType() != null){//idNumber
					List<ExaminationBatchComDO> examinationBatchComDO1 = examinationBatchService.selectType(li.getCompetitionType());
					if (examinationBatchComDO1.size() > 0){
						stuSignUpComVo.setCompetitionType(examinationBatchComDO1.get(0).getName());
					}
				}*/
				stuSignUpComVo.setCompetitionType(examinationBatchService.selectById(stuSignUpComDTO.getCbatchName()).getName());
				stuSignUpComVo.setCourt(li.getCourt());
				stuSignUpComVo.setFamily(li.getFamily());
				stuSignUpComVo.setProvince(li.getProvince());
				if(li.getSex()==1){
					stuSignUpComVo.setSex("男");
				}else if(li.getSex()==2){
					stuSignUpComVo.setSex("女");
				}else{
					stuSignUpComVo.setSex("未知");
				}
				list1.add(stuSignUpComVo);
			}

			//导出操作
			EasyPoiUtil.exportExcel(list1, "考生报名信息导出", "考生报名信息导出", StuSignUpComVo.class, "考生报名信息导出", response);
		}catch (Exception e){
			e.printStackTrace();
			return result.fail();
		}
		return result.ok();
	}


	/**
	 * A赛场第一次加密导出
	 *
	 * @param response
	 */
	@GetMapping("/downloadImportStuNum1")
	@RequiresPermissions("jzweb:stuSignUpCom:importNum1")
	@ResponseBody
	public Result<String> downloadImportNum1Template(HttpServletResponse response,StuSignUpComDO stuSignUpComDTO) {
		Result result = new Result();
		try {
			List<StuSignUpComNum1Vo> list1 = new LinkedList<>();
			Wrapper<StuSignUpComDO> wrapper = new EntityWrapper<StuSignUpComDO>().
					orderBy("id", false);
	/*		if(StringUtil.notEmpty(stuSignUpComDTO.getCompetitionType())){
				wrapper.addFilter("{0} like CONCAT('%',competition_type,'%')", stuSignUpComDTO.getCompetitionType());
			}*/
			if(StringUtil.notEmpty(stuSignUpComDTO.getName())){
				wrapper.like("name",stuSignUpComDTO.getName());
			}
			if(StringUtils.isNotBlank(stuSignUpComDTO.getCbatchName())){
				wrapper.eq("cbatch_id",stuSignUpComDTO.getCbatchName());
			}

			if(StringUtil.notEmpty(stuSignUpComDTO.getIdNumber())){
				wrapper.like("id_number", stuSignUpComDTO.getIdNumber());
			}
			wrapper.isNotNull("record_number");
			List<StuSignUpComDO> list=	stuSignUpComService.selectList(wrapper);
			for(StuSignUpComDO li:list){
				StuSignUpComNum1Vo stuSignUpComVo=new StuSignUpComNum1Vo();
				stuSignUpComVo.setRecordNumber(li.getRecordNumber());
				stuSignUpComVo.setNum1("-");
				if (StringUtil.isNotNull(li.getNum1())) {
					stuSignUpComVo.setNum1(li.getNum1());
				}
				list1.add(stuSignUpComVo);
			}

			//导出操作
			EasyPoiUtil.exportExcel(list1, "A赛场第一次加密导出", "A赛场第一次加密导出", StuSignUpComNum1Vo.class, "A赛场第一次加密导出", response);
		}catch (Exception e){
			e.printStackTrace();
			return result.fail();
		}
		return result.ok();
	}


	/** 选手管理批次搜索框查询接口 */
	@ResponseBody
	@PostMapping(value = "/cbatchList")
	public Result<?>  cbatchList(String types){
		//查询出所有考生批次
		Wrapper<ExaminationBatchComDO> wrapper = new EntityWrapper<>();
		wrapper.eq("type",3);
		wrapper.orderBy("id",false);
		if(StringUtils.isBlank(this.getUser().getTrack())){
			//身份为null或者""
			return Result.ok(examinationBatchService.selectList(wrapper));
		}
//		if (this.getUser().getTrack().equals("E")){
//				//竞赛一级管理员
//			wrapper.eq("create_id",this.getUserId());
//		}else if (this.getUser().getTrack().equals("D")){
//				//工作人员
//			wrapper.like("encipher",this.getUserId().toString());
//		}
		List<ExaminationBatchComDO> examinationBatchComDOS = examinationBatchService.selectList(wrapper);
		return Result.ok(examinationBatchComDOS);
	}




	@ResponseBody
	@GetMapping(value = "/list")
	@RequiresPermissions("jzweb:stuSignUpCom:stuSignUpCom")
	public Result<Object> list(StuSignUpComDO stuSignUpComDTO,String current,String number){//String current,String number
		if(StringUtils.isBlank(this.getUser().getTrack())){
			//身份为null或者""
			return Result.ok(stuSignUpComService.ListUstEb(Integer.parseInt(current), Integer.parseInt(number), stuSignUpComDTO));
		}
		if(this.getUser().getTrack().equals("E")){
			//一级管理员
			stuSignUpComDTO.setCreateId(this.getUserId().toString());
		}else if(this.getUser().getTrack().equals("D")){
			//工作人员
			stuSignUpComDTO.setEncipher(this.getUserId().toString());
		}
		Page<StuSignUpComDO> stuSignUpComDOPage = stuSignUpComService.ListUstEb(Integer.parseInt(current), Integer.parseInt(number), stuSignUpComDTO);
		return Result.ok(stuSignUpComDOPage);
	}

	@GetMapping("/add")
	@RequiresPermissions("jzweb:stuSignUpCom:add")
	String add(){

	    return "jzweb/stuSignUpCom/add";
	}


	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:stuSignUpCom:edit")
	String edit(@PathVariable("id") Long id,Model model){
		StuSignUpComDO stuSignUpCom = stuSignUpComService.selectById(id);
		model.addAttribute("stuSignUpCom", stuSignUpCom);
		return "jzweb/stuSignUpCom/edit";
	}


	@Log("添加考生报名")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:stuSignUpCom:add")
	public Result<String> save( StuSignUpComDO stuSignUpCom){
		//如果查询不到数据直接给值为0
		int maxNum= Optional.ofNullable(stuSignUpComService.MaxNum(stuSignUpCom.getCbatchId())).orElse(0);
		ExaminationBatchComDO examinationBatchComDO=examinationBatchService.selectById(stuSignUpCom.getCbatchId());
		if(examinationBatchComDO==null){
			return Result.fail("出现了错误，考试批次不存在！");
		}
		if(StringUtils.isBlank(examinationBatchComDO.getCompetitionName())){
			return Result.fail("未录入竞赛编号无法进行录入！");
		}
		stuSignUpCom.setState(3);
		if(stuSignUpCom.getTypes()==3){
			stuSignUpCom.setCourt("A");
		}
		Integer nums=maxNum+1;
		String comName=examinationBatchComDO.getCompetitionName()+"00"+nums;
		stuSignUpCom.setComNum(nums);
		stuSignUpCom.setComNums(comName);

		stuSignUpCom.setSignUpTime(new Date());
		stuSignUpComService.insert(stuSignUpCom);
        return Result.ok();
	}

	/**
	 * 理论赛道录入
	 * @param stuSignUpCom
	 * @return
	 */
	@Log("赛场录入")
	@ResponseBody
	@RequestMapping("/updateEnter")
	@RequiresPermissions("jzweb:stuSignUpCom:resetPwd")
	public Result<String>  updateEnter( StuSignUpComDO stuSignUpCom){
		StuSignUpComDO stuSignUpComDO1=	stuSignUpComService.selectById(stuSignUpCom.getId());
//		if(stuSignUpCom.getCourt()==null){
//			return  Result.fail("请录入赛道！");
//		}
//		if(stuSignUpCom.getNum1()==null){
//			return  Result.fail("请录入第一次加密！");
//		}
		if (stuSignUpCom.getNum1() !=null) {
			if (stuSignUpComDO1.getNum1() !=null) {
			 //传的字段和查出来的不一样说明修改过了
					Wrapper<StuSignUpComDO> wrapper = new EntityWrapper<>();
					wrapper.eq("court", stuSignUpComDO1.getCourt());
					wrapper.eq("cbatch_id", stuSignUpComDO1.getCbatchId());
					wrapper.eq("num1", stuSignUpCom.getNum1());
					List<StuSignUpComDO> list = stuSignUpComService.selectList(wrapper);
					if (list.size() > 0) {
						for (StuSignUpComDO li : list) {
							if (!li.getId().equals(stuSignUpCom.getId())) {
								return Result.fail("第一次加密序号重复！");
							}
						}
					}

			}else { //如果 == 空表示数据没有
				Wrapper<StuSignUpComDO> wrapper = new EntityWrapper<>();
				wrapper.eq("court", stuSignUpComDO1.getCourt());
				wrapper.eq("cbatch_id", stuSignUpComDO1.getCbatchId());
				wrapper.eq("num1", stuSignUpCom.getNum1());
				List<StuSignUpComDO> list = stuSignUpComService.selectList(wrapper);
				if (list.size() > 0) {
					for (StuSignUpComDO li : list) {
						if (!li.getId().equals(stuSignUpCom.getId())) {
							return Result.fail("第一次加密序号重复！");
						}
					}
				}
			}
		}

		if (stuSignUpCom.getNum2() !=null) {
			if (stuSignUpComDO1.getNum2() != null) {
				if (!stuSignUpComDO1.getNum2().equals(stuSignUpCom.getNum2())) { //传的字段和查出来的不一样说明修改过了
					Wrapper<StuSignUpComDO> wrapper = new EntityWrapper<>();
					wrapper.eq("court", stuSignUpComDO1.getCourt());
					wrapper.eq("cbatch_id", stuSignUpComDO1.getCbatchId());
					wrapper.eq("num2", stuSignUpCom.getNum2());
					List<StuSignUpComDO> list = stuSignUpComService.selectList(wrapper);
					if (list.size() > 0) {
						for (StuSignUpComDO li : list) {
							if (!li.getId().equals(stuSignUpCom.getId())) {
								return Result.fail("第二次加密序号重复！");
							}
						}
					}
				}
			} else {
				Wrapper<StuSignUpComDO> wrapper = new EntityWrapper<>();
				wrapper.eq("court", stuSignUpComDO1.getCourt());
				wrapper.eq("cbatch_id", stuSignUpComDO1.getCbatchId());
				wrapper.eq("num2", stuSignUpCom.getNum2());
				List<StuSignUpComDO> list = stuSignUpComService.selectList(wrapper);
				if (list.size() > 0) {
					for (StuSignUpComDO li : list) {
						if (!li.getId().equals(stuSignUpCom.getId())) {
							return Result.fail("第二次加密序号重复！");
						}
					}
				}
			}
			//在这里自动生成一个随机的密码
			Random random = new Random();
			String randomString = String.valueOf(random.nextInt(900000)+100000);
			stuSignUpCom.setRandomCipher(randomString);
		}
		boolean update = stuSignUpComService.updateById(stuSignUpCom);
		return update ? Result.ok() : Result.fail();
	}


	@Log("修改考生报名")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:stuSignUpCom:edit")
	public Result<String>  update( StuSignUpComDO stuSignUpCom){
		StuSignUpComDO stuSignUpComDO1=	stuSignUpComService.selectById(stuSignUpCom.getId());
		ExaminationBatchComDO examinationBatchComDO = examinationBatchService.selectById(stuSignUpCom.getCbatchId());
		Integer maxNum=stuSignUpComService.MaxNum(stuSignUpCom.getCbatchId());
		if(maxNum==null){
			maxNum=0;
		}
		Integer nums=maxNum+1;
		String comName=examinationBatchComDO.getCompetitionName()+"00"+nums;
		stuSignUpCom.setComNum(nums);
		stuSignUpCom.setComNums(comName);
		boolean update = stuSignUpComService.updateById(stuSignUpCom);
		return update ? Result.ok() : Result.fail();
	}
	
	@Log("删除考生报名")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:stuSignUpCom:remove")
	public Result<String>  remove( Long id){
		stuSignUpComService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除考生报名")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:stuSignUpCom:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		stuSignUpComService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}


	/**
	 * 导出错误信息
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 * @author kl
	 */
	@Log("导出错误信息")
	@GetMapping("/importComError")
	@ResponseBody
	@Transactional
	//@RequiresPermissions("jzweb:stuSignUp:import")
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("考生报名导入错误信息", "UTF-8") + ".xls");
		//编码
		response.setCharacterEncoding("UTF-8");
		String jsonArray = EhCacheUtil.get("stuSignComUp" + this.getUserId()).toString();
		JSONArray arrayList = JSONArray.parseArray(jsonArray);
		//转换为目标对象list
		List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
		workbook.write(response.getOutputStream());
	}

	/**
	 * 考生信息导入
	 *
	 * @param file excel文件
	 */
	@Log("考生信息导入")
	@PostMapping("/import")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:stuSignUpCom:import")
	public Result<?> importExcel(HttpServletRequest req, @RequestParam("file") MultipartFile file, String cbatchId,Integer type) {
		//---------------------------------检测导入信息及条件-----------------------------------------
		//第一步--判断文件格式
		if (!"application/vnd.ms-excel".equals(file.getContentType())) {
			return Result.fail("文件格式错误，请选择.xls文件");
		}

		//第二步--解析文件获得数据
		List<StuSignUpComVo> list = EasyPoiUtil.importExcel(file, 1, 1, StuSignUpComVo.class);
		//long num = list.stream().map(StuSignUpComVo::getIdNumber).distinct().count();
		if (list.size() == 0) {
			return Result.fail("Excel数据为空，请完善");
		}
//		if(num < list.size()){
//			return Result.fail("Excel数据有身份证号码重复");
//		}
		//查询考生数据
		List<StuSignUpComDO> signs = stuSignUpComService.selectList(new EntityWrapper<>());
		//验证是否与数据库考生重复
		if(!signs.isEmpty()){
			List<String> listMatch = list.stream().filter(d1->signs.stream().
					anyMatch(d2-> Objects.equals(d1.getIdNumber(),d2.getIdNumber()))).map(StuSignUpComVo::getIdNumber).collect(Collectors.toList());
			if(!listMatch.isEmpty()){
				return Result.fail(listMatch+"身份证号码已录入");
			}
		}


//		//第四步--判断该认证批次是否已经建立了理论考试批次；
//		//todo 目前定义为只要是认证批次，就一定存在理论考试
//		List<ExaminationBatchComDO> examinationBatchDO = examinationBatchService.findByKv("id", Long.parseLong(cbatchId), "type", 0);

		//---------------------------------验证数据并导入-----------------------------------------
		//数据该市行为第三行，第一行标题，第二行表头
		int startRow = 3;
		int cout = 1;//错误信息计数
		List<StuSignUpComDO> upDOList = new ArrayList<>();
		List<ErrorCodeVo> list1 = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			UserDO rrUserDo = null;
			UserDO rsUserDo = null;
			StringBuilder sb = new StringBuilder();
			//第一步验证是否存在空值
			if (StringUtils.isBlank(list.get(i).getName())) {
				sb.append("第" + (i + startRow) + "行姓名未填写，请完善！" + ";");
			} else {
				if (StringUtils.isBlank(list.get(i).getTicketNumber())) {
					sb.append("第" + (i + startRow) + "行准考证号未填写，请完善！" + ";");
				} else {
					if(1==2) {
						sb.append("第" + (i + startRow) + "行考场名称未填写，请完善！" + ";");
					}else {
						if (StringUtils.isBlank(list.get(i).getIdNumber())) {
							sb.append("第" + (i + startRow) + "行考生编号未填写，请完善！" + ";");
						} else {
										}

							if (sb.length() == 0) {
								//第四步排重验证（自身比较）
								for (int j = 0; j < list.size(); j++) {
									if (i != j) {
										if (list.get(i).getTicketNumber().equals(list.get(j).getTicketNumber())) {
											sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行准考证号重复，重复值：" + list.get(i).getIdNumber() + ";");
										}
									}
								}

								//第六步排重验证（和数据库比较），根据考生名称、考生身份证号码、该场考试的认证批次判断该考生是否已报名该考试
								StuSignUpComDO stuSignUpDO = stuSignUpService.findOneByKv("name", list.get(i).getName(), "id_number", list.get(i).getIdNumber(), "cbatch_id", Long.parseLong(cbatchId));
								if (stuSignUpDO != null) {
									sb.append("第" + (i + startRow) + "行考生已报名该次考试！" + ";");
								}

							}

						}
					}
				}

			if (sb.length() > 0) {
				ErrorCodeVo errorCodeVo = new ErrorCodeVo();
				errorCodeVo.setSeq(cout);
				cout += 1;
				errorCodeVo.setErrorCode(sb.toString());
				list1.add(errorCodeVo);
			} else {
				if (rrUserDo != null) {
					boolean cc = userService.insertNoPW(rrUserDo);
					if (!cc) {
					}
				}
			}

				StuSignUpComDO stuSignUpDO1 = new StuSignUpComDO();
				//stuSignUpDO1.setUserId(list.get(i).getTicketNumber());//准考证号
				stuSignUpDO1.setName(list.get(i).getName());//姓名
				stuSignUpDO1.setIdNumber(list.get(i).getIdNumber());//身份证号码
				stuSignUpDO1.setCbatchId(Long.parseLong(cbatchId));//认证批次id
				stuSignUpDO1.setSignUpTime(new Date());//报名时间

				stuSignUpDO1.setType(0);
				stuSignUpDO1.setState(3);//默认已分配
			if(StringUtils.isNotBlank(list.get(i).getSex())){
				if(list.get(i).getSex().equals("男")){
					stuSignUpDO1.setSex(1);
				}else if(list.get(i).getSex().equals("女")){
					stuSignUpDO1.setSex(2);
				}else{

				}
			}

			stuSignUpDO1.setFamily(list.get(i).getFamily());
			stuSignUpDO1.setProvince(list.get(i).getProvince());

			stuSignUpDO1.setTypes(type);
			if(type==3){
				stuSignUpDO1.setCourt("A");
			}else {
				stuSignUpDO1.setCourt(list.get(i).getCourt());
			}
			stuSignUpDO1.setUnitName(list.get(i).getUnitName());
			stuSignUpDO1.setTeacher(list.get(i).getTeacherName());


				stuSignUpDO1.setTicketNumber(list.get(i).getTicketNumber());//考号

				stuSignUpDO1.setCheckerId(this.getUserId());//默认审核人为导入者
				stuSignUpDO1.setCheckerDate(new Date());//默认审核时间为导入时间
			//将所属赛场文字转换为数据
			if(list.get(i).getCompetitionType() != null && list.get(i).getCompetitionType() != ""){
				if (list.get(i).getCompetitionType().equals("教师组")){
					//赋值为1
					stuSignUpDO1.setCompetitionType("1");
				}else if (list.get(i).getCompetitionType().equals("学生中职组")||list.get(i).getCompetitionType().equals("中职组")){
					//赋值为2
					stuSignUpDO1.setCompetitionType("2");
				}else if (list.get(i).getCompetitionType().equals("学生高职组")||list.get(i).getCompetitionType().equals("高职组")){
					//赋值为3
					stuSignUpDO1.setCompetitionType("3");
				}else if (list.get(i).getCompetitionType().equals("国际组")){
					//赋值为4
					stuSignUpDO1.setCompetitionType("4");
				}
			}

				upDOList.add(stuSignUpDO1);

			}


		Integer maxNum=stuSignUpComService.MaxNum(Long.valueOf(cbatchId));
		if(maxNum==null){
			maxNum=0;
		}
		ExaminationBatchComDO examinationBatchComDO=examinationBatchService.selectById(Long.valueOf(cbatchId));
		if(examinationBatchComDO==null){
			return Result.fail("出现了错误，考试批次不存在！");
		}
		if(StringUtils.isBlank(examinationBatchComDO.getCompetitionName())){
			return Result.fail("未录入竞赛编号无法进行录入！");
		}
		Integer nums=maxNum+1;
		//赋值竞赛编号
		for(StuSignUpComDO li:upDOList){

			String comName=examinationBatchComDO.getCompetitionName()+"00"+nums;
			li.setComNum(nums);
			li.setComNums(comName);
			nums++;
		}




		if (list1.size() == 0) {
			boolean c = stuSignUpService.insertBatch(upDOList, upDOList.size());
			if (c) {
				//ExaminationBatchComDO examinationBatchDOs = examinationBatchService.findOneByKv("cbatch_id", Long.parseLong(cbatchId), "type", 1);

				return Result.ok("成功导入" + list.size() + "条数据");
			} else {

				return Result.fail("报名信息导入错误，请稍后重试或联系管理员");
			}
		} else {


			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
			//将list1存到缓存中
			EhCacheUtil.put("stuSignComUp" + this.getUserId(), jsonArray);
			return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
		}
		}


	@Log("一键生成二次加密号和密码")
	@ResponseBody
	@GetMapping("/touchSign")
	public Result<?> touchSign(Long cbatchId){
		if (cbatchId==null){
			return Result.fail("请选择考试批次");
		}
		Wrapper<StuSignUpComDO> wrapper2 = new EntityWrapper<StuSignUpComDO>()
				//.eq("competition_type", 2)
				.eq("cbatch_id",cbatchId);
		List<StuSignUpComDO> signList2 = stuSignUpService.selectList(wrapper2);

		//判断规则是否为空
		String rule = getRule();
		if (StringUtils.isEmpty(rule)){
			return Result.fail("请先配置加密号规则");
		}

		if(null!=signList2 && !signList2.isEmpty()){
			int i = 1;
			for (StuSignUpComDO stuSignUpComDO : signList2) {
				Random random = new Random();
				String cipher = String.valueOf(random.nextInt(900000) + 100000);
				stuSignUpComDO.setRandomCipher(cipher);
				String num2 = "";
				String num1 = "";
				if(i<10){
					num2 = rule+"0"+i;
					num1 = "0"+i;
				}else{
					num2 = rule+i;
					num1 = String.valueOf(i);
				}
				stuSignUpComDO.setNum2(num2);
				stuSignUpComDO.setNum1(num1);
				i++;
			}
			stuSignUpService.updateBatchById(signList2);
		}
		return  Result.ok();
	}

	//查询二次加密规则
	public String getRule(){
		Map<String, String> map = new HashMap<>();
		map.put("name", "stu_num2");
		map.put("type", "stu_num2");
		return dictService.selDicBy(map);
	}


	@Log("一键解密")
	@PostMapping("/decrypt")
	@ApiOperation(value = "一键解密", notes = "一键解密")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "StuSignUpRequest", value = "StuSignUpRequest", required = true, dataType = "StuSignUpRequest")
	})
	@ResponseBody
	public Result<Object> decrypt(@RequestBody StuSignUpRequest stuSignUpRequest){
		return  Result.ok(stuSignUpService.updateBatchById(stuSignUpRequest.getStuSignUpComDOS()));
	}


	@Log("加密弹窗")
	@GetMapping("/encryptionJudge")
	public String encryptionJudge(){
		return "jzweb/encryptionJudge/encryptionJudge";
	}
}
